package com.example.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @program: sms
 * @description:
 * @author: zhanghz001
 * @create: 2020-11-04 10:54
 **/
// @WebFilter("/*")
public class FilterDemo04 implements Filter {
    private FilterConfig filterConfig;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("FilterDemo04 init");
        this.filterConfig = filterConfig;
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException,
            ServletException {
        //《代码题》
        // 1、
        //
        // 在网站中有一些数据是长时间不会发生变化的,比如图片,css文件,js文件.
        //
        // 因此,有一个需求是网页中的图片,css文件,js文件需要进行缓存.
        //
        // 请写一个过滤器实现以上需求,要求图片缓存1分钟,css文件缓存10分钟,js文件缓存20分钟
        //
        System.out.println("FilterDemo04 拦截了 filterDemo1  ");
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        String uri = request.getRequestURI();
        System.out.println(uri);
        if (uri.endsWith(".html")) {
            //
            // html文件缓存20分钟
            String html = filterConfig.getInitParameter("html");
            response.setDateHeader("Expires", System.currentTimeMillis() +
                    Integer.parseInt(html) * 60 * 1000);
        } else if (uri.endsWith(".css")) {
            String css = filterConfig.getInitParameter("css");
            // ,css文件缓存10分钟,
            response.setDateHeader("Expires", System.currentTimeMillis() +
                    Integer.parseInt(css) * 60 * 1000);

        } else if (uri.endsWith(".js")) {
            String js = filterConfig.getInitParameter("js");
            //图片缓存1分钟
            response.setDateHeader("Expires", System.currentTimeMillis() +
                    Integer.parseInt(js) * 60 * 1000);

        }
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
        System.out.println("FilterDemo04 destroy");

    }
}
